﻿@using OnWork.DataCenter.BLL.Standard;
@using OnWork.DataCenter.BLL.DataCenter;
@using OnWork.DataCenter.DAL.DataCenter;
@using OnWork.DataCenter.Utils.Caches;
@using SqlSugar;
@using Mapster;
@inherits ComponentBaseDataCenter;
<ValidateForm Model="@config"
              OnValidSubmit="@OnValidSubmit">
    <div class="row g-3 form-inline">
        <div class="col-12 col-sm-6">
            <Select PlaceHolder="请选择数据连接"
                    TValue="long"
                    IsSelectAllTextOnEnter="true" Items="@Conns" ShowSearch="true"
                    ShowLabel="true"
                    DisplayText="数据连接" @bind-Value="@config.DBID" OnSelectedItemChanged="OnSelectedItemChangedAsync" />
        </div>
        <div class="col-12 col-sm-6">
            <Select PlaceHolder="请选择执行类型" @bind-Value="@config.ConfigType" ShowLabel="true" DisplayText="操作类型" />
        </div>
        <div class="col-12">
            <BootstrapInputGroup >
                <BootstrapInputGroupLabel DisplayText="数据表名" />
                @*<label class="form-label">数据表名</label>*@
                <Select PlaceHolder="请选择表名"
                        TValue="string"
                        IsSelectAllTextOnEnter="true" @bind-Value="@config.DBTable" Items="@Tables" ShowSearch="true"
                        ShowLabel="true"
                        DisplayText="数据表名" />
                <Button Text="刷新" IsAsync="true" Icon="fa-solid fa-arrows-rotate" OnClick="@BtnLoadTableAsyncButton" />
            </BootstrapInputGroup>
        </div>
    </div>
    <div class="row" style="margin-top:1rem;">
        <Table TItem="DBCol" UseInjectDataService="false" IsPagination="false" DoubleClickToEdit="true"
               IsStriped="true" IsBordered="true" ShowSkeleton="true" IsMultipleSelect="true" ShowEmpty="false" ShowLoading="true" ShowColumnList="true"
               ShowToolbar="true" ShowExtendButtons="true"
               ShowSearch="false" ShowAdvancedSearch="false"
               AutoGenerateColumns="false" EditMode="EditMode.InCell"
               OnSaveAsync="@OnSaveAsync" OnDeleteAsync="@OnDeleteAsync"
               ShowToastAfterSaveOrDeleteModel="false" Items="@config.DBCols">
            <TableToolbarTemplate>
                <TableToolbarButton TItem="DBCol"
                                    Color="Color.Info"
                                    Icon="fas fa-bars-staggered"
                                    Text="加载表列"
                                                    IsAsync OnClickCallback="@BtnLoadColAsyncButton" />
            </TableToolbarTemplate>
            <TableColumns>
                <TableColumn Text="主键" @bind-Field="@context.IsPK" Width="65" />
                <TableColumn Text="数据库字段名" @bind-Field="@context.ColName" />
                <TableColumn Text="类型" @bind-Field="@context.ColType" Visible="true"/>
                <TableColumn Text="可空" @bind-Field="@context.IsNullable" Readonly="true" Width="65" />
                <TableColumn Text="DataTable列名称" @bind-Field="@context.ColSelectToken" />
                <TableColumn Text="说明" @bind-Field="@context.Remark" />
            </TableColumns>
            </Table>
        </div>
    <div class="form-footer mt-3">
        <DialogCloseButton />
        <Button Color="Color.Primary" ButtonType="ButtonType.Submit" Icon="fa-solid fa-floppy-disk" Text="保存" />
    </div>
</ValidateForm>


        @code {

    [CascadingParameter(Name = "BodyContext")]
    private object? Context { get; set; }

    [CascadingParameter]
    private Modal? Dialog { get; set; }

    [Parameter]
    public Action<DataTableToDBConfig>? OnSave { get; set; }

    private DataTableToDBConfig config;

    /// <summary>
    /// 依赖注入 数据库配置表
    /// </summary>
    [Inject]
    protected DSDataBaseBLL dsDataBaseBLL { get; set; }


    protected override void OnParametersSet()
    {
        base.OnParametersSet();

        if (Context is OnWork.DataCenter.BLL.Standard.DataTableToDBConfig)
        {
            config = Context as OnWork.DataCenter.BLL.Standard.DataTableToDBConfig;
            if (config!=null&&config.DBTable.IsNotEmptyOnWork())
            {
                Tables = new List<SelectedItem>() { new SelectedItem() { Text = config.DBTable, Value = config.DBTable } };
            }
        }
    }

    /// <summary>
    /// 数据库连接列表
    /// </summary>
    private List<SelectedItem> Conns;

    /// <summary>
    /// 数据库表名称
    /// </summary>
    private List<SelectedItem> Tables;

    /// <summary>
    /// 数据库连接
    /// </summary>
    private List<DSDataBase> dSDataBases;


    protected override void OnInitialized()
    {
        base.OnInitialized();
        //查询列表
        if (Conns is null)
        {
            dSDataBases = dsDataBaseBLL.GetALL();
            Conns = dSDataBases.Select(x => new SelectedItem() { Text = x.Name, Value = x.ID.ToString() }).ToList();
        }
    }


    /// <summary>
    /// 当选择项目修改时
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    private async Task OnSelectedItemChangedAsync(SelectedItem item)
    {
        try
        {
            var obj = dSDataBases.Where(x => x.ID == long.Parse(item.Value)).FirstOrDefault();
            if (obj != null)
            {
                config.DBConn = obj.ConnStr; //连接字符串
                config.DBType = (DbType)obj.Type; //数据库类型
            }
        }
        catch (Exception ex)
        {
            await base.MessageError(ex.ToString());
        }
    }

    /// <summary>
    /// 加载Table列表按钮
    /// </summary>
    /// <returns></returns>
    private async Task BtnLoadTableAsyncButton()
    {
        try
        {
            //获取数据库请求
            var db = SqlSugarCache.GetOrCreate(config.DBType, config.DBConn, config.DBID.ToString());
            if (db != null)
            {
                var tables = db.DbMaintenance.GetTableInfoList(false); //true 走缓存 false不走缓存
                if (tables != null)
                {
                    Tables = tables.Select(x => new SelectedItem() { Text = x.Name, Value = x.Name }).ToList();
                }
            }
        }
        catch (Exception ex)
        {
            await base.MessageError(ex.ToString());
        }
    }

    /// <summary>
    /// 加载Table 列
    /// </summary>
    /// <returns></returns>
    private async Task BtnLoadColAsyncButton(IEnumerable<DBCol> item)
    {
        try
        {
            //获取数据库请求
            var db = SqlSugarCache.GetOrCreate(config.DBType, config.DBConn, config.DBID.ToString());
            if (db != null)
            {
                var cols = db.DbMaintenance.GetColumnInfosByTableName(config.DBTable,false); //不使缓存
                if (cols != null)
                {
                    foreach (var c in cols)
                    {
                        DBCol col = new DBCol()
                            {
                                ColName = c.DbColumnName,
                                IsPK = c.IsPrimarykey,
                                Remark = c.ColumnDescription, //列描述
                                IsNullable = c.IsNullable,
                                ColSelectToken = c.DbColumnName,
                            };
                        var ishas = config.DBCols.Where(x => x.ColName == col.ColName).Any();
                        if (ishas == false)
                        {
                            config.DBCols.Add(col);
                        }
                    }
                }
            }
            base.StateHasChanged();//刷新页面
        }
        catch (Exception ex)
        {
            await base.MessageError(ex.ToString());
        }
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="item"></param>
    /// <param name="changedType"></param>
    /// <returns></returns>
    private async Task<bool> OnSaveAsync(DBCol item, ItemChangedType changedType)
    {
        //RESTfulResult<object> result;
        if (changedType == ItemChangedType.Update) // 更新
        {
            var entry = config.DBCols.Where(x => x.id == item.id).FirstOrDefault();

            item.Adapt(entry);
            return await Task.FromResult(true);
        }
        else //新增
        {
            config.DBCols.Add(item);
            return await Task.FromResult(true);
        }
    }

    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="items"></param>
    /// <returns></returns>
    private async Task<bool> OnDeleteAsync(IEnumerable<DBCol> items)
    {
        config.DBCols.RemoveAll(x => items.Contains(x));
        return await Task.FromResult(true);
    }

    private async Task OnValidSubmit(EditContext item)
    {
        if (config.ConfigType==DataTableToDBConfigType.UpdateInsert)
        {
            if(config.DBCols.Where(x => x.IsPK).Any() == false)
            {
                await ToastService?.Error("配置错误","更新并插入模式请至少设置一个主键!");
                return;
            }
        }
        OnSave(config);
        await Dialog.Close();
    }
}
